package com.ktjiaoyu.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

import java.text.SimpleDateFormat;
import java.util.Date;

public class BaseController {
    @InitBinder
    public void initBinder(WebDataBinder dataBinder){
        dataBinder.registerCustomEditor(Date.class,
                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }

    public String forward(String url){
        return UrlBasedViewResolver.FORWARD_URL_PREFIX+url;
    }
    public String redirect(String url){
        return UrlBasedViewResolver.REDIRECT_URL_PREFIX+url;
    }
    public HttpServletRequest request(){
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public void request(String name,Object obj){
        request().setAttribute(name, obj);
    }
    public <T> T request(String name){
        return (T) request().getAttribute(name);
    }
    public HttpSession session(){
        return request().getSession();
    }
    public void session(String name,Object obj){
        session().setAttribute(name, obj);
    }
    public <T> T session(String name){
        return (T) session().getAttribute(name);
    }
}
